package com.chushouya.order.service.api.impl;

import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Strings;
import com.chushouya.order.constants.LogisticsTypeEnum;
import com.chushouya.order.constants.OrderActionEnum;
import com.chushouya.order.constants.OrderStatusEnum;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.entity.OrderLogisticsEntity;
import com.chushouya.order.dao.repository.OrderLogisticsRepository;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.dto.api.push.OrderPushDataDTO;
import com.chushouya.order.dto.api.push.OrderPushRequestDTO;
import com.chushouya.order.service.api.OrderPushApiService;
import com.chushouya.order.service.common.CommonOrderActionService;
import com.chushouya.order.service.common.OrderLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Objects;

/**
 * 订单推送接口服务实现类
 * 处理来自合作商的订单状态推送通知
 * 
 * @author chushouya
 */
@Service
@Slf4j
public class OrderPushApiServiceImpl implements OrderPushApiService {

    @Resource
    private OrderRepository orderRepository;

    @Resource
    private OrderLogisticsRepository orderLogisticsRepository;

    @Resource
    private CommonOrderActionService commonOrderActionService;

    @Resource
    private OrderLogService orderLogService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String handleOrderPush(OrderPushRequestDTO pushRequest) {
        try {
            String notifyType = pushRequest.getNotifyType();
            String orderNo = pushRequest.getPartnerOrderNo();
            OrderPushDataDTO data = pushRequest.getData();

            // 验证推送类型
            if (Strings.isBlank(notifyType)) {
                throw Ex.business("推送类型不能为空");
            }

            // 验证合作商订单号
            if (Strings.isBlank(orderNo)) {
                throw Ex.business("合作商订单号不能为空");
            }

            // 获取订单信息
            OrderEntity order = getOrder(orderNo);

            // 根据推送类型处理不同的业务逻辑
            switch (notifyType) {
                case "DELIVERY": // 用户寄出回收产品
                    return handleDeliveryPush(order, data);
                case "DISPATCH": // 派单
                    return handleDispatchPush(order, data);
                case "CONFIRM": // 接单
                    return handleConfirmPush(order, data);
                case "VISIT": // 上门
                    return handleVisitPush(order, data);
                case "CANCEL": // 取消订单
                    return handleCancelPush(order, data);
                case "COMPLETE": // 订单完成
                    return handleCompletePush(order, data);
                case "CHANGE": // 订单变更
                    return handleChangePush(order, data);
                case "RECEIVE": // 订单已签收
                    return handleReceivePush(order, data);
                default:
                    throw Ex.business("未支持的推送类型: " + notifyType);
            }

        } catch (Exception e) {
            log.error("订单推送处理失败", e);
            throw Ex.business("订单推送处理失败: " + e.getMessage());
        }
    }

    /**
     * 处理用户寄出回收产品推送
     */
    private String handleDeliveryPush(OrderEntity order, OrderPushDataDTO data) {
        String remark = String.format("用户寄出回收产品，物流公司：%s，物流单号：%s",
                Strings.defaultString(data.getExpressCompany()),
                Strings.defaultString(data.getExpressNo()));

        // 更新订单状态为等待收货
        commonOrderActionService.receiveOrder(order, remark, OrderStatusEnum.WAIT_RECEIVE.value());

        // 保存快递信息到order_extend表
        if (Strings.isNotBlank(data.getExpressNo()) || Strings.isNotBlank(data.getExpressCompany())) {
            OrderLogisticsEntity logistics = new OrderLogisticsEntity();
            logistics.setOrderId(order.getOrderId());
            logistics.setExpressNo(data.getExpressNo());
            logistics.setExpressCompany(data.getExpressCompany());
            logistics.setType(LogisticsTypeEnum.USER_SEND.value());
            orderLogisticsRepository.insertSelective(logistics);
        }

        log.info("处理用户寄出回收产品推送成功，订单号：{}", order.getOrderNo());
        return "用户寄出回收产品推送处理成功";
    }

    /**
     * 处理订单派单成功推送
     */
    private String handleDispatchPush(OrderEntity order, OrderPushDataDTO data) {
        String remark = String.format("订单派单成功，工程师：%s，联系电话：%s",
                Strings.defaultString(data.getClerkName()),
                Strings.defaultString(data.getClerkPhone()));

        OrderEntity updateOrder = new OrderEntity();
        updateOrder.setOrderId(order.getOrderId());
        updateOrder.setClerkName(data.getClerkName());
        updateOrder.setClerkPhone(data.getClerkPhone());
        orderRepository.updateByPrimaryKeySelective(updateOrder);

        // 由于 dispatchOrder 需要 clerkId，这里先记录日志
        orderLogService.addOrderActionLog(order.getOrderId(), OrderActionEnum.DISPATCH_ORDER.value(), remark);

        log.info("处理订单派单成功推送成功，订单号：{}", order.getOrderNo());
        return "订单派单成功推送处理成功";
    }

    /**
     * 处理工程师接单推送
     */
    private String handleConfirmPush(OrderEntity order, OrderPushDataDTO data) {
        String remark = Strings.defaultString(data.getRemark(), "工程师接单");

        // 业务员接单
        commonOrderActionService.acceptOrder(order, remark, OrderStatusEnum.WAIT_VISIT.value());

        log.info("处理工程师接单推送成功，订单号：{}", order.getOrderNo());
        return "工程师接单推送处理成功";
    }

    /**
     * 处理工程师上门推送
     */
    private String handleVisitPush(OrderEntity order, OrderPushDataDTO data) {
        String remark = Strings.defaultString(data.getRemark(), "工程师上门");

        // 业务员上门
        commonOrderActionService.visitOrder(order, remark, OrderStatusEnum.WAIT_QUALITY.value());

        log.info("处理工程师上门推送成功，订单号：{}", order.getOrderNo());
        return "工程师上门推送处理成功";
    }

    /**
     * 处理订单取消推送
     */
    private String handleCancelPush(OrderEntity order, OrderPushDataDTO data) {
        String remark = Strings.defaultString(data.getRemark(), "订单取消");

        // 关闭订单
        commonOrderActionService.closeOrder(order, remark, OrderStatusEnum.CANCELLED.value());

        log.info("处理订单取消推送成功，订单号：{}", order.getOrderNo());
        return "订单取消推送处理成功";
    }

    /**
     * 处理订单完成推送
     */
    private String handleCompletePush(OrderEntity order, OrderPushDataDTO data) {
        BigDecimal completePrice = data.getCompletePrice() != null ? data.getCompletePrice() : BigDecimal.ZERO;
        String remark = String.format("订单完成，成交金额：%s，备注：%s",
                completePrice,
                Strings.defaultString(data.getRemark()));

        // 完成订单 - 这里使用默认支付方式，实际应根据业务需求调整
        commonOrderActionService.completeOrder(order, 1, completePrice, remark, OrderStatusEnum.COMPLETE.value());

        log.info("处理订单完成推送成功，订单号：{}", order.getOrderNo());
        return "订单完成推送处理成功";
    }

    /**
     * 处理订单信息变更推送
     */
    private String handleChangePush(OrderEntity order, OrderPushDataDTO data) {
        // 构建变更信息
        StringBuilder changeItems = new StringBuilder();
        if (Strings.isNotBlank(data.getUserPhone())) {
            changeItems.append("手机号：").append(data.getUserPhone()).append("，");
        }
        if (Strings.isNotBlank(data.getUserName())) {
            changeItems.append("姓名：").append(data.getUserName()).append("，");
        }
        if (Strings.isNotBlank(data.getUserAddress())) {
            changeItems.append("地址：").append(data.getUserAddress()).append("，");
        }
        if (data.getAppointStartTime() != null) {
            changeItems.append("预约开始时间：").append(data.getAppointStartTime()).append("，");
        }
        if (data.getAppointEndTime() != null) {
            changeItems.append("预约结束时间：").append(data.getAppointEndTime()).append("，");
        }

        String remark = "订单信息变更：" + changeItems.toString();
        
        // 记录订单日志
        orderLogService.addOrderActionLog(order.getOrderId(), OrderActionEnum.UPDATE_ORDER.value(), remark);

        log.info("处理订单信息变更推送成功，订单号：{}", order.getOrderNo());
        return "订单信息变更推送处理成功";
    }

    /**
     * 处理订单已签收推送
     */
    private String handleReceivePush(OrderEntity order, OrderPushDataDTO data) {
        String remark = String.format("订单已签收，签收时间：%s",
                data.getReceiveTime() != null ? data.getReceiveTime().toString() : "");

        // 确认收货
        commonOrderActionService.receiveOrder(order, remark, OrderStatusEnum.WAIT_QUALITY.value());

        log.info("处理订单已签收推送成功，订单号：{}", order.getOrderNo());
        return "订单已签收推送处理成功";
    }

    /**
     * 根据合作商订单号获取订单信息
     */
    private OrderEntity getOrderByPartnerOrderNo(String partnerOrderNo) {
        OrderEntity order = orderRepository.selectByPartnerOrderNo(partnerOrderNo);
        if (Objects.isNull(order)) {
            throw Ex.business("订单不存在，合作商订单号：" + partnerOrderNo);
        }
        return order;
    }

    /**
     * 根据订单号获取订单信息
     */
    private OrderEntity getOrder(String orderNo) {
        OrderEntity order = orderRepository.selectByOrderNo(orderNo);
        if (Objects.isNull(order)) {
            throw Ex.business("订单不存在，订单号：" + orderNo);
        }
        return order;
    }

    /**
     * 更新订单扩展信息
     */
    private void updateOrderExtend(Long orderId, String expressNo, String expressCompany) {
        try {

        } catch (Exception e) {
            log.error("更新订单扩展信息失败，订单ID：{}", orderId, e);
        }
    }
}
